package com.codegzy.controller;

import com.codegzy.entity.User;
import com.codegzy.service.UserService;
import com.codegzy.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("generateImageCode")
    public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {
        String code = VerifyCodeUtils.generateVerifyCode(4);
        session.setAttribute("code", code);
        response.setContentType("image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        VerifyCodeUtils.outputImage(220, 80, outputStream, code);
    }

    @RequestMapping("save")
    public String save(User user, String code, HttpSession session) throws UnsupportedEncodingException {
        try {
            String sessionCode = (String) session.getAttribute("code");
            if (!sessionCode.equalsIgnoreCase(code)) {
                throw new RuntimeException("验证码输入不一致");
            }
            userService.save(user);
        } catch (Exception e) {
            return "redirect:/register?msg=" + URLEncoder.encode(e.getMessage(), "UTF-8");
        }
        return "redirect:/login";
    }

    @RequestMapping("login")
    public String login(String username, String password, HttpSession session) throws UnsupportedEncodingException {
        User user = userService.findByUsernameAndPassword(username, password);
        try {
            if (ObjectUtils.isEmpty(user)) {
                throw new RuntimeException("用户名或密码输入错误");
            }
        } catch (Exception e) {
            return "redirect:/login?msg=" + URLEncoder.encode(e.getMessage(), "UTF-8");
        }
        session.setAttribute("user", user);
        return "redirect:/employee/findAll";
    }
}
